package com.dongnao.network.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {
    public static void main(String[] args) throws IOException {
        //创建服务器，监听9999端口
        ServerSocket serverSocket = new ServerSocket(9999);
        //在程序即将关闭时，关闭一个 serverSocket 实例
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                serverSocket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }));
        System.out.println("服务器启动成功");
        while (true) {
            //监听与这个套接字的连接并接受他
            Socket request = serverSocket.accept();
            System.out.println(request.toString());
            try {
                //获取字节输入流
                InputStream inputStream = request.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
                String msg, rsp = "";
                while ((msg = bufferedReader.readLine()) != null) {
                    if (msg.length() == 0) break;
                    rsp += msg;
                    System.out.println(msg);
                }
                System.out.println("服务器收到数据" + rsp);
            } catch (Exception e) {
                System.out.println(e);
            } finally {
                request.close();
            }
        }
    }
}
